import 'package:flutter/material.dart';
import 'package:flutter_account_book/utils/alert.dart';

import 'package:flutter_account_book/utils/db/entities/record_type.dart';
import 'package:flutter_account_book/widgets/custom_icon.dart';
import 'package:flutter_account_book/widgets/keyboard.dart';
import 'package:flutter_account_book/widgets/pick_list.dart';
import 'package:omni_datetime_picker/omni_datetime_picker.dart';
import 'package:get/get.dart';

import 'logic.dart';

class AddRecordPage extends StatefulWidget {
  const AddRecordPage({super.key});

  @override
  State<StatefulWidget> createState() => _AddRecordPage();
}

class _AddRecordPage extends State<AddRecordPage>
    with TickerProviderStateMixin {
  late AddRecordLogic _logic;
  late AnimationController _animationController;

  @override
  void initState() {
    super.initState();
    _logic = Get.put(AddRecordLogic());

    _animationController = AnimationController(
        vsync: this, duration: const Duration(milliseconds: 500))
      ..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          //动画执行结束时反向执行动画
          _animationController.reverse();
        } else if (status == AnimationStatus.dismissed) {
          //动画恢复到初始状态时执行动画（正向）
          _animationController.forward();
        }
      });
    // 启动动画
    _animationController.forward();
  }

  @override
  void dispose() {
    _animationController.stop();
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final themeData = Theme.of(context);

    return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          backgroundColor: Colors.white,
          automaticallyImplyLeading: false,
          actions: [
            IconButton(
                onPressed: () {
                  Get.back();
                },
                icon: const Icon(
                  Icons.close,
                  color: Colors.black,
                ))
          ],
        ),
        body: SafeArea(
          child: Column(
            children: [
              Row(
                children: [
                  Expanded(
                      child: Obx(() => TextButton.icon(
                          onPressed: () {
                            _logic.loadData(0);
                          },
                          label: Text(
                            '支出',
                            style: TextStyle(
                                fontSize: 16,
                                color: _logic.state.isIncome.value == 1
                                    ? null
                                    : themeData.primaryColor),
                          )))),
                  const VerticalDivider(width: 0.5),
                  Expanded(
                      child: Obx(() => TextButton.icon(
                          onPressed: () {
                            _logic.loadData(1);
                          },
                          label: Text('收入',
                              style: TextStyle(
                                  fontSize: 16,
                                  color: _logic.state.isIncome.value == 1
                                      ? themeData.primaryColor
                                      : null)))))
                ],
              ),
              const Padding(padding: EdgeInsets.all(5)),
              Expanded(
                  child: Padding(
                      padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
                      child: Obx(() => GridView.builder(
                            gridDelegate:
                                const SliverGridDelegateWithFixedCrossAxisCount(
                                    crossAxisCount: 5),
                            itemCount: _logic.state.list.length,
                            itemBuilder: (context, index) {
                              RecordType type = _logic.state.list[index];
                              return Obx(() => Container(
                                  color:
                                      _logic.state.selectedId.value == type.id
                                          ? themeData.highlightColor
                                          : null,
                                  child: InkWell(
                                      onTap: () {
                                        _logic.setSelected(type);
                                      },
                                      child: Column(
                                        mainAxisAlignment:
                                            MainAxisAlignment.center,
                                        children: [
                                          type.type == 0
                                              ? CustomIcon.asset(type.iconPath,
                                                  size: CustomIconSize.middle,
                                                  backgroundColor: Color(
                                                      type.backgroundColorHex),
                                                  color:
                                                      Color(type.textColorHex))
                                              : CustomIcon.text(type.iconPath,
                                                  size: CustomIconSize.middle,
                                                  backgroundColor: Color(
                                                      type.backgroundColorHex),
                                                  color:
                                                      Color(type.textColorHex)),
                                          Text(type.name)
                                        ],
                                      ))));
                            },
                          )))),
              const Divider(height: 0.5),
              Expanded(
                  child: Column(
                children: [
                  InkWell(
                    onTap: () async {
                      String? remark = await showTextAlertDialog(
                          context: context,
                          defaultValue: _logic.state.remark.value,
                          title: "请输入",
                          placeholder: "备注...");
                      if (remark != null) {
                        _logic.state.remark.value = remark;
                      }
                    },
                    child: Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 16),
                        child: Container(
                          alignment: Alignment.center,
                          height: 44,
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: <Widget>[
                              Expanded(
                                child: Obx(() => Text(
                                      _logic.state.remark.isEmpty
                                          ? '备注...'
                                          : _logic.state.remark.value,
                                      overflow: TextOverflow.ellipsis,
                                      maxLines: 1,
                                      textAlign: TextAlign.right,
                                      style: TextStyle(
                                          fontSize: 16,
                                          color: _logic.state.remark.isEmpty
                                              ? Colors.grey
                                              : Colors.black),
                                    )),
                              )
                            ],
                          ),
                        )),
                  ),
                  Row(
                    children: [
                      Padding(
                          padding: const EdgeInsets.only(left: 12),
                          child: InkWell(
                            onTap: () async {
                              _logic.setDateTime(await showOmniDateTimePicker(
                                  context: context,
                                  lastDate: DateTime.now(),
                                  is24HourMode: true));
                            },
                            borderRadius: BorderRadius.circular(15),
                            child: Container(
                              alignment: Alignment.center,
                              padding:
                                  const EdgeInsets.symmetric(horizontal: 12),
                              height: 30,
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(15),
                                  border: Border.all(
                                      color: Colors.grey, width: 0.6)),
                              child: Obx(
                                  () => Text(_logic.state.dateString.value)),
                            ),
                          )),
                      Padding(
                          padding: const EdgeInsets.only(left: 12),
                          child: InkWell(
                            onTap: () async {
                              PickItem? item = await showDialog(
                                  context: context,
                                  builder: (builder) => PickList(
                                      title: "选择支付方式",
                                      defalutValue: _logic.pay.id,
                                      items: _logic.state.payMethods
                                          .map<PickItem>((item) => PickItem(
                                              value: item.id,
                                              label: item.name,
                                              image: item.iconPath != null
                                                  ? Image.asset(
                                                      item.iconPath!,
                                                      width: 20,
                                                      height: 20,
                                                    )
                                                  : null,
                                              obj: item))
                                          .toList()));
                              if (item != null) {
                                _logic.setPay(item.obj);
                              }
                            },
                            borderRadius: BorderRadius.circular(15),
                            child: Container(
                              alignment: Alignment.center,
                              padding:
                                  const EdgeInsets.symmetric(horizontal: 12),
                              height: 30,
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(15),
                                  border: Border.all(
                                      color: Colors.grey, width: 0.6)),
                              child: Obx(() => Row(
                                    children: [
                                      SafeArea(
                                          child: _logic.state.payIcon.isNotEmpty
                                              ? Image.asset(
                                                  _logic.state.payIcon.value,
                                                  width: 20,
                                                  height: 20,
                                                )
                                              : SizedBox(
                                                  width: 20,
                                                  height: 20,
                                                )),
                                      const SizedBox(width: 10),
                                      Text(_logic.state.payName.value)
                                    ],
                                  )),
                            ),
                          )),
                      Expanded(
                        flex: 1,
                        child: Padding(
                          padding: const EdgeInsets.only(right: 4),
                          child: Obx(() => Text(
                                _logic.state.numberString.isEmpty
                                    ? '0.0'
                                    : _logic.state.numberString.value,
                                style: const TextStyle(fontSize: 18),
                                maxLines: 1,
                                textAlign: TextAlign.right,
                                overflow: TextOverflow.ellipsis,
                              )),
                        ),
                      ),
                      AnimatedBuilder(
                        animation: _animationController,
                        builder: (BuildContext context, Widget? child) {
                          return Container(
                            margin: const EdgeInsets.only(right: 14),
                            width: 2,
                            height: 25,
                            decoration: BoxDecoration(
                                color: themeData.primaryColor.withOpacity(
                                    0.8 * _animationController.value)),
                          );
                        },
                      ),
                    ],
                  ),
                  const Padding(padding: EdgeInsets.symmetric(vertical: 3)),
                  const Divider(height: 0.3),
                  Obx(() => NumberKeyboard(
                        isAdd: _logic.state.isAdd.value,
                        // 键盘输入
                        numberCallback: (number) =>
                            _logic.inputVerifyNumber(number),
                        // 删除
                        deleteCallback: () {
                          if (_logic.state.numberString.isNotEmpty) {
                            _logic.state.numberString.value =
                                _logic.state.numberString.value.substring(0,
                                    _logic.state.numberString.value.length - 1);
                          }
                        },
                        // 清除
                        clearZeroCallback: () {
                          _logic.clearZero();
                        },
                        // 等于
                        equalCallback: () {
                          _logic.addNumber();
                        },
                        //继续
                        nextCallback: () async {
                          if (_logic.state.isAdd.value == true) {
                            _logic.addNumber();
                          }
                          await _logic.record();
                          _logic.clearZero();
                        },
                        // 保存
                        saveCallback: () async {
                          await _logic.record();
                          Get.back();
                        },
                      ))
                ],
              ))
            ],
          ),
        ));
  }
}
